package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.exception.LyException;
import com.leyou.user.dto.UserDto;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import com.leyou.utils.RegexUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Boolean exists(String data, Long type) {

        Boolean flag = false;
        //用户名查询
        if (1 == type) {
            int size = query().eq("username", data).list().size();
            if (size > 0) {
                flag = true;
            }
            return flag;

        } else if (2 == type) {
            //手机号查询
            int size = query().eq("phone", data).list().size();
            if (size > 0) {
                flag = true;
            }
            return flag;
        }else {
            return flag;
        }
    }

    @Override
    public UserDto queryUserByUsernameAndPassword(String username, String password) {

        List<User> users = query().eq(null != username, "username", username).list();
        if (users.size() > 0) {
            User user = users.get(0);
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            if (matches) {
                return new UserDto(user);
            }else {
                throw  new LyException(400, "用户名和密码不匹配");
            }

        }else{
            throw new LyException(400,"无此用户");
        }


    }

    @Override
    public void sendCode(String phone) {
        final String KEY_PREFIX = "001";
        //验证是否是手机号码
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }
        //使用Apachede的工具类生成6为数字验证码
        String code = RandomStringUtils.randomNumeric(6);

        String key =KEY_PREFIX+phone;
        //设置5秒后销毁
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        // 4.发送RabbitMQ消息到ly-sms
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);

    }

    @Override
    public void addUser(String username, String password, String phone, String code) {

        // 1.校验验证码
        // 1.1 取出redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get("001" + phone);
        // 1.2 比较验证码
        if (!StringUtils.equals(code, cacheCode)) {
            throw new LyException(400, "验证码错误");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setPhone(phone);

        save(user);
    }
}
